import { readdir, stat } from 'node:fs/promises'
import { extname, join } from 'node:path'
import { shell } from 'electron'

export async function getApps (
  path: string,
  appList: IApp[] = [],
): Promise<IApp[]> {
  try {
    const fileNames = await readdir(path)
    for (const fileName of fileNames) {
      const filePath = join(path, fileName)
      const res = await stat(filePath)
      if (res.isFile()) {
        const appName = fileName.replace(extname(fileName), '')
        const appDetail = shell.readShortcutLink(filePath)
        if (!appDetail || !appDetail.target || appDetail.target.toLowerCase().includes('unin')) {
          throw new Error(`cannot read app '${appName}' information`)
        }
        appList.push({
          desc: appDetail.target,
          type: 'app',
          name: appName,
          icon: '',
        })
      } else if (res.isDirectory()) {
        return getApps(filePath, appList)
      }
    }
    return appList
  } catch (e) {
    return Promise.reject(e)
  }
}
